package com.dflc.controller.SystemController;

import com.dflc.annotations.CheckUser;
import com.dflc.entity.po.TFileAttachmentData;
import com.dflc.entity.rep.HttpResponseEntity;
import com.dflc.entity.vo.TAudioDataVo;
import com.dflc.mapper.TFileAttachmentDataMapper;
import com.dflc.service.TFileAttachmentDataService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import javax.annotation.Resource;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * 文件管理
 * @author tqx
 * @site tqx
 * @company 数字涪陵
 */
@RestController
@Slf4j
@RequestMapping("/fileController")
public class FileController {

    @Resource
    private TFileAttachmentDataService tAudioDataService;

    @Resource
    private TFileAttachmentDataMapper tFileAttachmentDataMapper;

    @Value("${file.path}")
    private String saveDir;

    /**
     * @param file 文件
     * @return HttpResponseEntity<String>
     * @author oyt
     * @date 2025年07月20日 14:54
     * Description: 上传文件
     */
    @PostMapping("/fileUpload")
    @CheckUser
    public HttpResponseEntity upload(@RequestBody MultipartFile file) {
        if (ObjectUtils.isEmpty(file))
            return HttpResponseEntity.error(500, "上传文件不能为空!");
        String originalFilename = file.getOriginalFilename();
        String baseName = FilenameUtils.getBaseName(originalFilename);
        String fileType = FilenameUtils.getExtension(originalFilename);
        String fileName = baseName + UUID.randomUUID() + "." + fileType;
        long fileSizeInBytes = file.getSize();
        // 完整的保存路径
        String saveFilePath = saveDir + fileName;
        try {
            InputStream inputStream = file.getInputStream();
            // 创建文件输出流
            FileOutputStream fileOutputStream = new FileOutputStream(saveFilePath);
            // 读取并写入文件内容
            byte[] buffer = new byte[4096];
            int bytesRead = -1;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
            }
            // 关闭流
            fileOutputStream.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            return HttpResponseEntity.error(500, "文件上传失败");
        }
        TFileAttachmentData audioData = new TFileAttachmentData();
        audioData.setUrl(saveFilePath);
        audioData.setFileName(fileName);
        audioData.setOrgFileName(originalFilename);
        audioData.setFileSize(fileSizeInBytes);
        tAudioDataService.save(audioData);
        return HttpResponseEntity.success(audioData);
    }

    /**
     * @param id 文件id
     * @return HttpResponseEntity
     * @author oyt
     * @date 2025年07月20日 14:54
     * Description: 根据文件ID删除文件
     */
    @GetMapping("/deleteFile")
    @CheckUser
    public HttpResponseEntity deleteFile(@RequestParam(value = "id") Integer id) {
        try {
            //查询账号信息根据openId
            TFileAttachmentData audioData = tAudioDataService.getById(id);
            if (audioData == null) {
                return HttpResponseEntity.error(500, "没找到该文件的信息");
            }
            if (tAudioDataService.removeById(id)) {
                File file = new File(audioData.getUrl());
                if (file.exists()) {
                    if (file.delete()) {
                        log.info("删除文件源成功");
                    } else {
                        log.info("删除文件源失败");
                        return HttpResponseEntity.error(500, "删除文件源失败");
                    }
                }
            } else {
                return HttpResponseEntity.error(500, "删除文件数据失败");
            }
        } catch (Exception e) {
            return HttpResponseEntity.error(500, e.getMessage());
        }
        return HttpResponseEntity.success("删除文件成功!");
    }

    /**
     * @param businessType 业务类型
     * @param businessId   业务ID
     * @return HttpResponseEntity
     * @author oyt
     * @date 2025年07月20日 14:54
     * Description: 获取附件列表根据业务类型和业务id
     */
    @GetMapping("/getFile")
    @CheckUser
    public HttpResponseEntity getFile(@RequestParam(value = "businessType") Integer businessType, @RequestParam(value = "businessId") Integer businessId) {
        try {
            List<TAudioDataVo> voList = tFileAttachmentDataMapper.findByBusinessTypeAndBusinessId(businessType, businessId);
            if (voList.isEmpty())
                return HttpResponseEntity.error(500, "没找到该文件信息");
            return HttpResponseEntity.success(voList);
        } catch (Exception e) {
            return HttpResponseEntity.error(500, e.getMessage());
        }
    }


    /**
     * @param id 文件id
     * @return HttpResponseEntity
     * @author oyt
     * @date 2025年07月20日 14:54
     * Description: 根据文件id下载文件
     */
    @GetMapping("fileDownload/{id}")
    @CheckUser
    public ResponseEntity<StreamingResponseBody> fileDownload(@PathVariable("id") Integer id) throws IOException {
        TFileAttachmentData tAudioData = tAudioDataService.getById(id);
        if (tAudioData == null)
            return ResponseEntity.notFound().build();
        File file = new File(tAudioData.getUrl());
        if (!file.exists())
            return ResponseEntity.notFound().build();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(tAudioData.getOrgFileName(), "UTF-8"));
        StreamingResponseBody body = outputStream -> {
            try (InputStream in = new FileInputStream(file)) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }
        };
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .body(body);
    }




    /**
     * 根据类型及业务主键获取附件材料
     *
     * @param type,id
     * @return HttpResponseEntity
     * @author wfh
     * @date 2025/8/21 11:30
     * Description:  根据类型及业务主键获取附件材料
     */
    @GetMapping("/getFileByTypeAndId/{type}/{id}")
    @CheckUser
    public HttpResponseEntity getFileByTypeAndId(@PathVariable("type") Integer type,@PathVariable("id") Integer id) {
        try {
            Map<String, Object> params2 = new HashMap<>();
            params2.put("businessId", id);
            params2.put("businessType", type);
            List<TAudioDataVo> voList = tFileAttachmentDataMapper.findAllByMap2(params2);
            if (voList.isEmpty())
                return HttpResponseEntity.error(500, "没找到该文件信息");
            return HttpResponseEntity.success(voList);
        } catch (Exception e) {
            return HttpResponseEntity.error(500, e.getMessage());
        }
    }
}
